﻿using System;
using System.ComponentModel;
using System.Web.UI;
using Library.WebControls.Ds;
using Library.WebControls.SimpleCombobox;
using System.Web.UI.WebControls;

namespace Library.WebControls.SimpleGridView {
	/// <summary>
	/// Extend combobox grid column
	/// </summary>
	//[ParseChildren(true, "EditCombobox")]
	[ParseChildren(typeof(SpExCombobox))]
	//	[PersistChildren(true)]
	//[PersistChildren(true)]
	public class SpGvExComboxColumn : SpGvBaseColumn {
		/// <summary>
		/// create extend combobox grid column
		/// </summary>
		public SpGvExComboxColumn() {
			EditCombobox = new CbEditTextEdit(this);
			EditValueMode = EditValueMode.Attribute;
		}
		/// <summary>
		/// Get column type
		/// </summary>
		public override GridColumnType ColumnType {
			get { return GridColumnType.ExComboEdit; }
		}
		/// <summary>
		/// 
		/// </summary>
		[PersistenceMode(PersistenceMode.InnerProperty)]
		[MergableProperty(false)]

		[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
		public SpExCombobox EditCombobox { get; private set; }

		internal override BaseControl CreateClientEditControl() {
			return EditCombobox;
		}
		private class CbEditTextEdit : SpExCombobox {
			private readonly SpGvExComboxColumn _column;
			public CbEditTextEdit(SpGvExComboxColumn column) {
				_column = column;
			}

			public override bool Visible {
				get { return _column.Visible; }
				set {

				}
			}
			[Browsable(false)]
			[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
			[EditorBrowsable(EditorBrowsableState.Never)]
			public override string ID {
				get {
					return base.ID;
				}
				set {
					base.ID = value;
				}
			}
		}


		public Unit Height {
			get { return EditCombobox.Height; }
			set { EditCombobox.Height = value; }
		}

		public Unit Width {
			get { return EditCombobox.Width; }
			set { EditCombobox.Width = value; }
		}
		protected override string GetTextFromObject(object value) {
			InitDataSourceWrapper();
			while (_dataSourceWrapper.MoveNext()) {
				var fieldValue = _dataSourceWrapper.Current.GetPropertyValue(EditCombobox.ValueField);
				if (fieldValue != null && fieldValue.Equals(value)) {
					object result = _dataSourceWrapper.Current.GetPropertyValue(EditCombobox.TextField);
					return base.GetTextFromObject(result);
				}
			}
			return base.GetTextFromObject(value);
		}

		private void InitDataSourceWrapper() {
			if (_dataSourceWrapper == null) {
				if (EditCombobox.DataSource == null) {
					_dataSourceWrapper = DataSourceWrapper.Emplty;
				} else {
					_dataSourceWrapper = new DataSourceWrapper(EditCombobox.DataSource);
				}

			}
			_dataSourceWrapper.Reset();
		}

		private DataSourceWrapper _dataSourceWrapper;
		protected override string GetValueFromObject(object value) {
			if (value == null) return String.Empty;
			return value.ToString();
		}
	}
}
